/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 27 juin 2010, 08:33:24
 */

package darknet.gui;

import darknet.DarknetRegistry;
import darknet.core.impl.FacadeImpl;
import darknet.core.spec.Facade;
import darknet.application.chat.gui.ChatApplicationPanel;
import darknet.application.chat.spec.ChatApplication;
import darknet.gui.core.PreferencesPanel;
import darknet.gui.wizard.firstrun.WizardFirstRunDialog;
import java.awt.BorderLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Yoyo
 */
public class MainFrame extends javax.swing.JFrame {

    /** Serial version */
    private static final long serialVersionUID = 1L;

    /** The application Registry */
    private DarknetRegistry registry;

    /** The facade of the system. */
    private Facade facade;

    /** Preferences Panel */
    private PreferencesPanel preferencesPanel;

    /** The Chat application panel */
    private ChatApplicationPanel chatApplicationPanel;

    /** Creates new form MainFrame */
    public MainFrame() {

        try {
	    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	} catch (ClassNotFoundException e) {
	} catch (InstantiationException e) {
	    throw new RuntimeException(e);
	} catch (IllegalAccessException e) {
	    throw new RuntimeException(e);
	} catch (UnsupportedLookAndFeelException e) {
	    throw new RuntimeException(e);
	}

        String workingDirectory = System.getProperty("user.dir")
                + File.separator + "conf";
        
        // Get the registry.
	if (!new File(workingDirectory).exists()) {
	    new WizardFirstRunDialog(this).setVisible(true);
	} else {

            // Create the Facade and the Registry.
            registry = new DarknetRegistry(workingDirectory);
            try {
                facade = new FacadeImpl(
                        registry.getWorkingDirectory().getAbsolutePath(),
                        registry.getUsername(),
                        registry.getPassword(),
                        registry.getAddress(),
                        registry.getPort());
                
            } catch (FileNotFoundException e) {

                JOptionPane.showMessageDialog(
                        null, "An error occur while starting core services : \n"
                        + e.getLocalizedMessage(), "Darknet 0.1 - Fatal error",
                        JOptionPane.ERROR_MESSAGE);
                System.exit(-1);
                
            } catch (IOException e) {

                JOptionPane.showMessageDialog(
                        null, "An error occur while starting core services : \n"
                        + e.getLocalizedMessage(), "Darknet 0.1 - Fatal error",
                        JOptionPane.ERROR_MESSAGE);
                System.exit(-1);
            }
        }

        // Create GUI Component.
        preferencesPanel = new PreferencesPanel(facade);

        ChatApplication chatApplication = facade.getChatApplication();
	chatApplicationPanel = new ChatApplicationPanel(chatApplication);
        chatApplication.addChatObserver(chatApplicationPanel);

        initComponents();
    }

    public void setFacade(Facade facade) {
        if (facade == null) {
            throw new IllegalArgumentException("facade is null");
        }
        this.facade = facade;
    }

    /**
     * Attach a panel onto the body.
     *
     * @param panel
     */
    private void showPanel(JPanel panel) {

	this.invalidate();
	bodyPanel.removeAll();
        bodyPanel.setLayout(new BorderLayout());
	bodyPanel.add(panel, BorderLayout.CENTER);
	this.validate();
	this.repaint();
    }

    /**
     * Attach the chat panel onto the body.
     */
    public void showChatPanel() {
	showPanel(chatApplicationPanel);
    }

    public void showPreferencesPanel() {
        showPanel(preferencesPanel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bodyPanel = new javax.swing.JPanel();
        menuBar = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        menuItemQuit = new javax.swing.JMenuItem();
        menuApplications = new javax.swing.JMenu();
        menuItemChat = new javax.swing.JMenuItem();
        menuTools = new javax.swing.JMenu();
        menuItemPreferences = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Darknet 0.1");

        javax.swing.GroupLayout bodyPanelLayout = new javax.swing.GroupLayout(bodyPanel);
        bodyPanel.setLayout(bodyPanelLayout);
        bodyPanelLayout.setHorizontalGroup(
            bodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 800, Short.MAX_VALUE)
        );
        bodyPanelLayout.setVerticalGroup(
            bodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 579, Short.MAX_VALUE)
        );

        menuFile.setMnemonic('f');
        menuFile.setText("File");

        menuItemQuit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK));
        menuItemQuit.setText("Quit");
        menuItemQuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemQuitActionPerformed(evt);
            }
        });
        menuFile.add(menuItemQuit);

        menuBar.add(menuFile);

        menuApplications.setMnemonic('a');
        menuApplications.setText("Application");

        menuItemChat.setText("Chat");
        menuItemChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemChatActionPerformed(evt);
            }
        });
        menuApplications.add(menuItemChat);

        menuBar.add(menuApplications);

        menuTools.setText("Tools");

        menuItemPreferences.setText("Preferences");
        menuItemPreferences.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemPreferencesActionPerformed(evt);
            }
        });
        menuTools.add(menuItemPreferences);

        menuBar.add(menuTools);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(bodyPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(bodyPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuItemQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemQuitActionPerformed
        System.exit(0); // TODO Better way to stop an application ?
    }//GEN-LAST:event_menuItemQuitActionPerformed

    private void menuItemPreferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemPreferencesActionPerformed
        showPreferencesPanel();
    }//GEN-LAST:event_menuItemPreferencesActionPerformed

    private void menuItemChatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemChatActionPerformed
        showChatPanel();
    }//GEN-LAST:event_menuItemChatActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel bodyPanel;
    private javax.swing.JMenu menuApplications;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenuItem menuItemChat;
    private javax.swing.JMenuItem menuItemPreferences;
    private javax.swing.JMenuItem menuItemQuit;
    private javax.swing.JMenu menuTools;
    // End of variables declaration//GEN-END:variables

}
